package com.itkjb.leisurely.resource.sys.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itkjb.leisurely.core.base.BaseConstants;
import com.itkjb.leisurely.core.base.BaseDto;
import com.itkjb.leisurely.core.base.BaseResult;
import com.itkjb.leisurely.core.base.controller.BaseController;
import com.itkjb.leisurely.core.log.annotion.LeisurelyRequestLog;
import com.itkjb.leisurely.core.util.RequestUserInfoUtil;
import com.itkjb.leisurely.resource.sys.model.SysRoleModel;
import com.itkjb.leisurely.resource.sys.model.properties.ResourceWebConfig;
import com.itkjb.leisurely.resource.sys.service.ISysRoleService;
import com.itkjb.leisurely.resource.sys.service.support.DepIdsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
 * <p>
 * 用户角色 接口层
 * </p>
 *
 * @author itkjb.com
 * @since 2020-06-25
 */
@RestController
@RequestMapping("/sys/sys-role")
@Api(value="用户角色",tags={"用户角色相关接口"})
public class SysRoleController extends BaseController<SysRoleModel,ISysRoleService> {

    @Autowired
    ResourceWebConfig resourceWebConfig;
    /**
     * 内置角色类型
     */
    public static int INNER_ROLE_TYPE = 16;
    /**
     * 获取用户角色列表
     * @param param 查询通用参数
     * @param model 特定条件参数
     * @param request
     * @param response
     * @return
     */
    @GetMapping
    @ApiOperation(value="获取用户角色列表",notes="支持分页参数")
    @PreAuthorize("hasAnyAuthority('SysRole','SysRole:query') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<IPage<SysRoleModel>> page(BaseDto param, SysRoleModel model, HttpServletRequest request, HttpServletResponse response){
        BaseResult<IPage<SysRoleModel>> res = new BaseResult<>();
        if(StringUtils.isBlank(model.getDepId())){
            DepIdsUtil.buildModelWithAllPermissionDepIds(model);
        }else{
            boolean contains = DepIdsUtil.getAllPermissionDepIds().contains(model.getDepId());
            if(!contains){
                res.setMsg("没有权限查询该组织下的角色数据");
                return res;
            }
        }
        res = super.page(param, model);
        return res;
    }

    /**
     * 获取用户角色列表
     * @param param 查询通用参数，分页参数不可用
     * @param model 特定条件参数
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value="获取用户角色列表",notes="不支持分页")
    @PreAuthorize("hasAnyAuthority('SysRole','SysRole:query') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<List<SysRoleModel>> list(BaseDto param,SysRoleModel model, HttpServletRequest request, HttpServletResponse response){
        BaseResult<List<SysRoleModel>> res = new BaseResult<>();
        // 代码生成器生成的下面执行结果默认关闭，防止获取非法数据和数据量过大，若需要手动打开，并做好防护措施
        // DepIdsUtil.buildModelWithCurrentDepIds(model);
        if(StringUtils.isBlank(model.getDepId())){
            DepIdsUtil.buildModelWithAllPermissionDepIds(model);
        }else{
            boolean contains = DepIdsUtil.getAllPermissionDepIds().contains(model.getDepId());
            if(!contains){
                res.setMsg("没有权限查询该组织下的角色数据");
                return res;
            }
        }
        return super.list(param, model);
    }

    /**
     * 新增用户角色
     * @param param
     * @param request
     * @param response
     * @return
     */
    @PostMapping
    @ApiOperation(value="新增用户角色",notes="")
    @PreAuthorize("hasAnyAuthority('SysRole:add') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysRoleModel> add(@Valid @RequestBody SysRoleModel param, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysRoleModel> res = new BaseResult<>();
        boolean contains = false;
        if(StringUtils.isBlank(param.getDepId())){
            param.setDepId(RequestUserInfoUtil.getRequestUserInfoModel().getCurrentDepId());
            contains = true;
        }else{
            contains = DepIdsUtil.getAllPermissionDepIds().contains(param.getDepId());
        }
        if(!contains){
            res.setMsg("暂无权限为该组织添加角色");
        }else if(isInnerRoleCode(param.getCode())){
            res.setMsg("该角色编码不可用，请更换");
        }else{
            res = super.add(param);
        }

        return res;
    }

    /**
     * 获取用户角色详情
     * @param id
     * @param response
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value="获取用户角色详情",notes="")
    @ApiParam(name = "id",type = "Serializable",required = true)
    @PreAuthorize("hasAnyAuthority('SysRole:info') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysRoleModel> info(@PathVariable("id") Serializable id, HttpServletResponse response){
        BaseResult<SysRoleModel> res = new BaseResult<>();
        res = super.info(id);
        return res;
    }

    /**
     * 修改用户角色
     * @param param
     * @param request
     * @param response
     * @return
     */
    @PutMapping
    @ApiOperation(value="修改用户角色",notes="")
    @PreAuthorize("hasAnyAuthority('SysRole:edit') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysRoleModel> edit(@RequestBody SysRoleModel param,HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysRoleModel> res = new BaseResult<>();
        if(StringUtils.isBlank(param.getId())){
            res.setMsg("请指定要修改的角色");
        }else{
            if(StringUtils.isNotBlank(param.getDepId())){
                if(!DepIdsUtil.getCurrentDepIds().contains(param.getDepId())){
                    //param.setDepId(RequestUserInfoUtil.getRequestUserInfoModel().getCurrentDepId());
                    res.setMsg("不能指定该组织");
                    return res;
                }
            }
            SysRoleModel byId = this.baseService.getById(param.getId());
            if(byId.getType() == INNER_ROLE_TYPE){
                // 如果是内置角色，将角色编码置空，不让修改
                param.setCode(null);
            }else if(isInnerRoleCode(param.getCode())){
                // 如果修改为内部角色代码，不让修改
                res.setMsg("该角色编码不可用，请更换");
                return res;
            }
            if(StringUtils.isBlank(byId.getDepId()) && StringUtils.isBlank(param.getDepId())){
                param.setDepId(RequestUserInfoUtil.getRequestUserInfoModel().getCurrentDepId());
            }else if(StringUtils.isBlank(byId.getDepId())){
                param.setDepId(param.getDepId());
            }
            res =  super.edit(param);

        }
        return res;
    }

    /**
     * 判断是否是内部角色
     * @param roleCode
     * @return
     */
    protected boolean isInnerRoleCode(String roleCode){
        boolean bln = false;
        if(resourceWebConfig !=null && resourceWebConfig.getInnerRoleCode()!=null && resourceWebConfig.getInnerRoleCode().size()>0){
            for (String s : resourceWebConfig.getInnerRoleCode()) {
                if(s.equals(roleCode)){
                    bln = true;
                    break;
                }
            }
        }
        return bln;
    }

    /**
     * 删除用户角色
     * @param ids
     * @param request
     * @param response
     * @return
     */
    @DeleteMapping
    @ApiOperation(value="删除用户角色",notes="注意参数是数字，就算单个，也要以数字的形式传递")
    @PreAuthorize("hasAnyAuthority('SysRole:del') || hasRole('"+ BaseConstants.ADMINISTRATOR_ROLE_CODE +"') ")
    public BaseResult<SysRoleModel> delete(@RequestBody String[] ids, HttpServletRequest request, HttpServletResponse response){
        BaseResult<SysRoleModel> res = new BaseResult<>();
        List<String> strings = Arrays.asList(ids);
        List<SysRoleModel> temRoles = this.baseService.listByIds(strings);
        boolean bln = true;
        if(temRoles !=null && temRoles.size()>0){
            for (SysRoleModel temRole : temRoles) {
                if(temRole.getType() == INNER_ROLE_TYPE){
                    bln = false;
                    break;
                }
            }
        }
        if(bln){
            res = super.delete(ids);
        }else{
            res.setMsg("删除的角色中不能包含内置角色");
        }
        return res;
    }
    //******************//

    /**
     * 根据组织id 获取当前组织可用的角色
     * @param depId
     * @return
     */
    @GetMapping("/listForDepEnable")
    @ApiOperation(value="根据组织id 获取当前组织可用的角色",notes="不需要权限，但需要登陆")
    @LeisurelyRequestLog(paramsName = "depId")
    public BaseResult<List<SysRoleModel>> listForDepEnable(@RequestParam("depId") String depId){
        BaseResult<List<SysRoleModel>> res = new BaseResult<>();
        //DepIdsUtil.getAllPermissionDepIds().contains(depId);
        List<SysRoleModel> sysRoleModels = this.baseService.listForDepEnable(depId);
        res.toSuccess().setData(sysRoleModels);
        return res;
    }

}

